import re

import requests

from unit_tools.handle_data.configParse import ConfigParse
from unit_tools.handle_data.yaml_handler import read_yaml, write_yaml, clear_yaml


class SendRequests:

    def __init__(self):
        pass

    @classmethod
    def _test_encode(cls, res_text):
        """
        处理接口返回值出现unicode编码时，如：\\u767b
        :param res_text:
        :return:
        """
        match = re.search(r"\\u[0-9a-fA-F]", res_text)
        if match:
            result = res_text.encode().decode("unicode_escape")
        else:
            result = res_text
        return result

    def send_request(self, **kwargs):
        # 创建session会话
        session = requests.session()
        response = None
        try:
            response = session.request(**kwargs)
            # 获取cookie
            set_cookie = requests.utils.dict_from_cookiejar(response.cookies)
            if set_cookie:
                # print(f"获取到cookie：{set_cookie}")
                write_yaml({"Cookie":set_cookie})
            result = self._test_encode(response.text)
            print(result)
        except requests.exceptions.ConnectionError:
            print("接口请求异常，可能是request的连接数过多或者速度过快导致程序报错！")
        except requests.exceptions.RequestException as e:
            print("请求异常，请检查系统或数据是否正常！原因{e}")

        return response

    def excute_api_request(self, api_name, url, method, header, case_name, cookie=None, file=None, **kwargs):
        """
        发送接口请求
        :param api_name: 接口名称
        :param url: 接口地址
        :param method: 请求方法
        :param header: 请求头
        :param case_name: 测试用例名称
        :param cookie: cookie
        :param file: 文件上传
        :param kwargs: 未知参数关键数
        :return:
        """
        response = self.send_request(method=method, url=url, headers=header, cookies=cookie, files=file, timeout=10,
                                     verify=False,
                                     **kwargs)
        return response


if __name__ == '__main__':
    data = read_yaml(".././data/login.yaml")[0]
    conf = ConfigParse()
    url = conf.get_host("host")+data["baseInfo"]["url"]
    method = data["baseInfo"]["method"]
    header = data["baseInfo"]["header"]
    res_data = data["testCase"][0]["data"]

    send = SendRequests()
    res = send.excute_api_request(api_name=None, url=url, method=method, header=header, case_name=None,
                                  data=res_data)
    res_json = res.json()
    token = res_json["token"]
    userid = res_json["userId"]
    write_yaml({"token":token,"userid":userid})
